let contractId;
let productOrderId;
let returnMoneyId,productName,finishOrderProductNum,orderId,orderNumber,customerPayId;//回款id,产品名称,产品号
let currentIframe = $(getIframeByElement(document.body));
let currentRoute = currentIframe.attr("src");
let baseInfo = getParamsObj(currentRoute);
let flowId = baseInfo.flowId?baseInfo.flowId:'';
//当前关联流水
let relationParams=function(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;
    params.flowId = flowId;
    return params
};
//操作记录
let activeParams=function(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;
    params.sortOrder = params.order;
    params.flowId = flowId;
    params.orderNumber = '';
    params.payNumber = '';
    return params
};
$(function () {
    // 起止日期
    assignment();
    //获取当前用户信息
    getCurrentInfo();
})
function assignment(){
    $.ajax({
        url: '/bankFlow/queryInfo',
        type: 'GET',
        dataType: 'json',
        data: {
            flowId:flowId
        },
        success:(function(data) {
            if(data.code == '000000') {
                baseInfo=data.data;
                //基本信息赋值 赋值节点的id和数据中的key一致
                let demos=$(".contractTypeContainer>.form-group");
                for(let i=0;i<demos.length;i++){
                    if(demos.eq(i).find("span").length==1){
                        var id=demos.eq(i).find("span").attr('id');
                        demos.eq(i).find("span").text(baseInfo[id]);
                    }else{
                        var id=demos.eq(i).find("textarea").attr('id');
                        demos.eq(i).find("textarea").text(baseInfo[id]);
                    }
                }
                if(baseInfo['relationState']=='N'||baseInfo['relationState']=='B'){
                    $("#relationBtn").show();
                    getBankRelateSwitch()
                }else{
                    $("#relationBtn").hide()
                }
                tableList('relationTable','/bankFlow/query/relate',relationColumns,relationParams);
                tableList('activeRecordTable','/bankFlow/query/operatorLog',activeColumns,activeParams);

            }
        }),
        error:(function() {
            $.alert('请求错误');
        })
    })

}
function getBankRelateSwitch(){
    $.ajax({
        url: '/systemParameterSetting/selectSystemParameterSetting',
        type: 'GET',
        dataType: 'json',
        success:(function(data) {
            if(data.code=='000000'){
                if(data.data.bankRelateSwitch=='N'){
                    $("#relationBtn").hide()
                }
            }else{
                $.alert(data.message)
            }
        }),
        error:(function(data) {
            $.alert('请求失败')
        })
    })
}

//将路由上的参数转为对象的形式
function getParamsObj(currentRoute){
    if(currentRoute.indexOf("?")){
        let paramsStr=currentRoute.substring(currentRoute.indexOf("?")+1);
        let paramsArr=paramsStr.split('&');
        let obj={};
        for(var i=0;i<paramsArr.length;i++){
            var paramItem=paramsArr[i];
            var key=paramItem.split('=')[0];
            var value=paramItem.split('=')[1]=='null'?'':paramItem.split('=')[1];
            obj[key]=value;
        }
        return obj

    }else{
        return {};
    }
}

let format = {
    operate: function (value, row) {
        let examineState;
        let currentState=row.examState;
        switch(currentState){
            case 0:
                examineState='<button type="button" class="btn btn-default" id="relieveBtn">解除关联</button>';
                break;
            case 1:
                examineState='<button type="button" class="btn btn-warning">正在审核</button>';
                break
        }
        return examineState;
    },
    activeOperate:function (value, row) {
        let operatorTypeName;
        switch(row.operatorTypeName){
            case '1':
                operatorTypeName='修改';
                break;
            case '2':
                operatorTypeName='删除';
                break;
            case '3':
                operatorTypeName='退款';
                break;
            case '4':
                operatorTypeName='关联';
                break;
            case '5':
                operatorTypeName='调减';
                break;

        }
        return  operatorTypeName;
    },
};
window.operateEvents = {
    //查看点击事件
    'click #relieveBtn': function (e, value, row, index) {
        relieveRelation(row.returnMoneyId,row.productName,row.finishOrderProductNum,row.productOrderId,row.orderNumber,row.customerPayId)
    }
}
//相关流水信息
let relationColumns=[
    {
        title: '序号', align: 'left', valign: 'middle', width: '50',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    {title: '订单编号/充值码', field: 'orderNumber', align: 'left', valign: 'middle',formatter: function (value, row, index) {
            var fileValue='-';
            if(row.relateType=='D'){
                fileValue=row.orderNumber
            }else if(row.relateType=='F'){
                fileValue=row.payNumber
            }
            return fileValue;
        }},
    {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
    {title: '产品号', field: 'finishOrderProductNum', align: 'left', valign: 'middle'},
    {title: '到款金额', field: 'arriveMoney', align: 'left', valign: 'middle'},
    {title: '到款时间', field: 'arriveTime', align: 'left', valign: 'middle'},
    {title: '录入人', field: 'inputName', align: 'left', valign: 'middle'},
    {title: '操作', field: 'examineState', align: 'right', valign: 'middle',events: operateEvents, formatter: format.operate}];

//修改记录
let activeColumns=[
    {
        title: '序号', align: 'left', valign: 'middle', width: '50',
        formatter: function (value, row, index) {
            return index + 1;
        }},
    {title: '回款编号', field: 'arriveNum', align: 'left', valign: 'middle'},
    {title: '动作', field: 'operatorTypeName', align: 'left', valign: 'middle',formatter: format.activeOperate},
    {title: '修改前信息', field: 'formerData', align: 'left', valign: 'middle', formatter : function(value, row, index, field){
            var values=value?value:'-';
            return `<span style='display: inline-block;overflow: hidden;text-overflow: ellipsis;max-width:inherit;white-space: nowrap;' data-toggle='tooltip' data-placement="top" data-original-title="${values}">${values}</span>`;
        },
        cellStyle : function(value, row, index, field){
            return {
                css: {
                    "white-space": "nowrap",
                    "text-overflow": "ellipsis",
                    "overflow": "hidden",
                    "max-width":"200px"
                }
            };
        }},
    {title: '修改后信息', field: 'newData', align: 'left', valign: 'middle', formatter : function(value, row, index, field){
            var values=value?value:'-';
            return `<span style='display: inline-block;overflow: hidden;text-overflow: ellipsis;max-width:inherit;white-space: nowrap;' data-toggle='tooltip' data-placement="top" data-original-title="${values}">${values}</span>`;
        },
        cellStyle : function(value, row, index, field){
            return {
                css: {
                    "white-space": "nowrap",
                    "text-overflow": "ellipsis",
                    "overflow": "hidden",
                    "max-width":"200px"
                }
            };
        }},
    {title: '修改时间', field: 'createTm', align: 'left', valign: 'middle'},
    {title: '修改人', field: 'createPeopleName', align: 'left', valign: 'middle'},
];


function tableList(domId,url,columns,queryParams) {
    $(`#${domId}`).bootstrapTable('destroy');
    $(`#${domId}`).bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: url,
        method: 'get',                                      // 请求方式
        contentType: 'application/x-www-form-urlencoded',   // 请求内容类型
        dataType: 'json',                                   // 数据类型
        striped: true,                                      // 是否显示行间隔色
        sortable: true,                                     // 是否启用排序
        sortOrder: 'desc',                                  // 排序方式
        sortName: 'createTm',                               // 排序字段
        cache: false,                                       // 是否使用缓存
        showColumns: false,                                 // 显示隐藏列
        showRefresh: false,                                 // 显示刷新按钮
        showToggle: false,                                  // 切换显示样式
        showFooter: false,                                  // 显示Table脚部
        pagination: true,                                   // 是否显示分页
        showPaginationSwitch: false,                        // 是否显示分页按钮
        clickToSelect: true,                                // 是否启用点击选中行
        maintainSelected: true,                             // 分页是否保留选中
        singleSelect: false,
        undefinedText: '-',                                 // cell没有值时显示
        sidePagination: 'server',                           // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'transactionNo',
        idField: 'transactionNo',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber:domId=='relationTable'?1:0,    // 右侧固定列
        queryParams: queryParams,  // 查询参数
        columns: columns,
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            $("[data-toggle='tooltip']").tooltip({
                "container": 'body',
            })
        },
        onLoadError: function (status) {
            if (status == 403) {
                $.alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                $.alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

//打开关联流水页面
function openRelationModal(){
    openTab('流水关联','/front/finance/relate?'+currentRoute.substring(currentRoute.indexOf("?")+1));}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}
/*打开解除关联*/
function relieveRelation(returnMoneyIds,productNames,finishOrderProductNums,orderIds,orderNumbers,customerPayIds){
    $("#relieveReason").val('');
    returnMoneyId = returnMoneyIds;
    productName = productNames;
    finishOrderProductNum = finishOrderProductNums;
    orderId = orderIds;
    orderNumber = orderNumbers;
    customerPayId = customerPayIds;
    $("#relieveRelationModal").modal("show");
    var bootstrapValidator = $("#relieveRelationForm").data('bootstrapValidator');
    if (bootstrapValidator) {
        $("#relieveRelationForm").data('bootstrapValidator').destroy();
        $('#relieveRelationForm').data('bootstrapValidator', null);
    }
    relieveRelationFormValidator();

}
//提交解除关联
function submitRelieveRelation(){
    // 验证表单
    var bootstrapValidator = $("#relieveRelationForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    };
    let params = {
        flowId:flowId,
        returnMoneyId:returnMoneyId,
        productName:productName,
        finishOrderProductNum:finishOrderProductNum,
        orderId:orderId,
        orderNumber:orderNumber,
        customerPayId:customerPayId,
        reason:$.trim($("#relieveReason").val())
    };
    $.ajax({
        url: '/bankFlow/relieve',
        type: 'POST',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(params),
        success:(function(data) {
            if(data.code=='000000'){
                tableList('relationTable','/bankFlow/query/relate',relationColumns,relationParams);
                tableList('activeRecordTable','/bankFlow/query/operatorLog',activeColumns,activeParams);
                $("#relieveRelationModal").modal("hide");
            }else{
                $.alert(data.data)
            }
        }),
        error:(function() {
            $.alert('请求错误');
        })
    })

}

//解除关联字段校验
function relieveRelationFormValidator(){
    $('#relieveRelationForm').bootstrapValidator({
        fields: {
            relieveReason: {
                validators: {
                    notEmpty: {
                        message: '解除原因不能为空'
                    }
                }
            }
        }
    })
}

//获取当前用户信息
function getCurrentInfo(){
    $.ajax({
        url: '/sysCompany/currentInfo',
        type: 'GET',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {},
        success: (function (data) {
            if(data.code=='000000'){
                if(data.data.deptId == 3){
                    $('#subtractBtn').show()
                }
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}

//弹出流水调减窗口
function openSubtractModal(){
    validatorStart('subtractForm',subtractFormValidator);
    $("#subtractModal input").val('');
    $("#subtractModal textarea").val('');
    $('#subtractModal').modal('show');
}

function validatorStart(formId,validatorFun){
    var reasonFormValidator = $(`#${formId}`).data('bootstrapValidator');
    if (reasonFormValidator) {
        $(`#${formId}`).data('bootstrapValidator').destroy();
        $(`#${formId}`).data('bootstrapValidator', null);
    }
    validatorFun()
}

//流水调减表单校验
function subtractFormValidator(){
    $('#subtractForm').bootstrapValidator({
        fields: {
            modifyMoney: {
                validators: {
                    notEmpty: {
                        message: '调减金额不能为空'
                    }
                }
            },
            modifyReason: {
                validators: {
                    notEmpty: {
                        message: '调减原因不能为空'
                    }
                }
            }
        }
    })
}

//校验是否通过
function bootstrapValidatorFlag(formId){
    console.log(formId)
    console.log($(`#${formId}`))
    var bootstrapValidator = $(`#${formId}`).data('bootstrapValidator');
    console.log(bootstrapValidator)
    bootstrapValidator.validate();
    return bootstrapValidator.isValid()
}

//流水调减
function subtract(){
    var flag = bootstrapValidatorFlag('subtractForm');
    if(!flag){
        return;
    }
    var modifyMoney = $.trim($("#modifyMoney").val());
    if(Number(modifyMoney)<=0){
        $.alert("调减金额必须大于0")
        return;
    }
    $.ajax({
        url: '/bankFlow/subAvailableAmount',
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {
            flowId:flowId,
            modifyMoney:modifyMoney,
            modifyReason:$.trim($("#modifyReason").val())
        },
        success: (function (data) {
            if(data.code=='000000'){
                $.alert("调减成功");
                $("#subtractModal").modal('hide');
                assignment();
            }else{
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}
